package com.school.controller;

import com.school.entity.User;
import com.school.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/userinfo")
public class UserInfoController {
    @Autowired
    private UserRepository userRepository;

    @GetMapping("/me")
    public Map<String, Object> getMyInfo(@SessionAttribute(value = "user", required = false) User user) {
        Map<String, Object> result = new HashMap<>();
        if (user == null) {
            result.put("success", false);
            result.put("message", "未登录");
            return result;
        }
        result.put("success", true);
        result.put("user", user);
        return result;
    }

    @PostMapping("/update")
    public Map<String, Object> updateMyInfo(@SessionAttribute(value = "user", required = false) User user, @RequestBody Map<String, String> form) {
        Map<String, Object> result = new HashMap<>();
        if (user == null) {
            result.put("success", false);
            result.put("message", "未登录");
            return result;
        }
        if (form.containsKey("name")) user.setName(form.get("name"));
        if (form.containsKey("phone")) user.setPhone(form.get("phone"));
        userRepository.save(user);
        result.put("success", true);
        result.put("user", user);
        return result;
    }
}
